//
//  NetWorkHandler.m
//  UI20_豆瓣电影storyBoard
//
//  Created by 王阳阳 on 16/1/4.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NetWorkHandler.h"

@implementation NetWorkHandler

+ (void)GETWithURL:(NSString *)str completion:(NETBLOCK)netBlock
{
    NSString *urlstr = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];
    NSURL *url = [NSURL URLWithString:urlstr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"%@",error);
            }
            else
            {
                NSError *jerro = nil;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jerro];
                if (jerro) {
                    NSLog(@"%@",jerro);
                }
                else
                {
                    netBlock(result);
                }
            }
            
        });
    }];
    [task resume];
}


+(void)POSTWithURL:(NSString *)str body:(NSData *)body completion:(NETBLOCK)netBlock
{
    NSString *urlstr = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"POST";
    request.HTTPBody = body;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"%@",error);
            }
            else
            {
                NSError *jerro = nil;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jerro];
                if (jerro) {
                    NSLog(@"%@",jerro);
                }
                else
                {
                    netBlock(result);
                }
            }
            
        });
    }];
    [task resume];
}
@end
